package top.yangyitao.dao.impl;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import top.yangyitao.dao.UserDao;
import top.yangyitao.model.User;

@Repository("userDao")
public class UserDaoImpl implements UserDao {

	@Resource
	private SessionFactory sessionFactory;
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public User findUserByUserName(String userName) {
		Session session = sessionFactory.getCurrentSession();
		String hql = "from User u where u.userName = "+"'"+userName+"'";
		Query query = session.createQuery(hql);
		List<User> list = query.list();
		if(list.size()>0)
			return list.get(0);
		else
			return null;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public User findUserByEmail(String email) {
		Session session = sessionFactory.getCurrentSession();
		String hql = "from User u where u.email = "+"'"+email+"'";
		Query query = session.createQuery(hql);
		List<User> list = query.list();
		if(list.size()>0)
			return list.get(0);
		else
			return null;
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public void deleteUserByUserName(String userName) {
		Session session = sessionFactory.getCurrentSession();
		String hql = "delete from User u where u.userName = '"+userName+"'";
		Query query = session.createQuery(hql);
		query.executeUpdate();
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void updateUserOfPassword(User user) {
		Session session = sessionFactory.getCurrentSession();
		String hql = "update User u set u.password = '"+user.getPassword()+"' where u.userName = '"+user.getUserName()+"'";
		Query query = session.createQuery(hql);
		query.executeUpdate();
	}
	
	@Override
	public Serializable insertUser(User user) {
		Session session = sessionFactory.getCurrentSession();
		return session.save(user);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public List<User> getAllUser() {
		Session session = sessionFactory.getCurrentSession();
		String hql = "from User";
		Query query = session.createQuery(hql);
		List<User> list = query.list();
		return list;
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public void activeUser(String userName) {
		Session session = sessionFactory.getCurrentSession();
		String hql = "update User u set u.flag = 1 where u.userName = '"+userName+"'";
		Query query = session.createQuery(hql);
		query.executeUpdate();
	}
}
